package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.CheckGroupDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service(interfaceClass = CheckGroupService.class)
@Transactional
public class CheckGroupServiceImpl implements CheckGroupService {
    @Resource
    private CheckGroupDao checkGroupDao;

    /**
     * 新增检查组，同时要让检查组关联检查项
     * @param checkGroup
     * @param checkitemIds
     */
    @Override
    public void add(CheckGroup checkGroup, Integer[] checkitemIds) {
        //新增检查组，操作t_checkgroup表
        checkGroupDao.add(checkGroup);

        setCheckGroupAndCheckItem(checkGroup,checkitemIds);
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        PageHelper.startPage(currentPage,pageSize);
        Page<CheckGroup> page = checkGroupDao.findPage(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public CheckGroup findById(Integer id) {
        return checkGroupDao.findById(id);
    }

    @Override
    public List<Integer> findItemIdsByGroudId(String id) {
        return checkGroupDao.findItemIdsByGroudId(id);
    }

    @Override
    public void edit(CheckGroup checkGroup, Integer[] checkitemIds) {
        //更新基本信息
        checkGroupDao.edit(checkGroup);
        //根据检查组id删除中间表数据（清理原有关联关系）
        checkGroupDao.deleteAssociation(checkGroup.getId());
        //将修改后的关系设置上去
        setCheckGroupAndCheckItem(checkGroup,checkitemIds);
    }

    @Override
    public List<CheckGroup> findAll() {
        return checkGroupDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        //根据检查组id查询是否有关联的检查项
        List<Integer> list = checkGroupDao.findItemIdsByGroudId(id + "");
        if (list.size()>0){
            throw new RuntimeException("当前检查组被引用，不能删除");
        }
        checkGroupDao.delete(id);
    }

    public void setCheckGroupAndCheckItem(CheckGroup checkGroup,Integer[] checkitemIds){
        //获得新增检查组的id
        Integer checkGroupId = checkGroup.getId();
        //设置检查组和检查项的多对多的关联关系，操作t_checkgroup_checkitem表
        if (checkitemIds!=null&&checkitemIds.length>0){
            for (Integer checkitemId : checkitemIds) {
                checkGroupDao.setCheckGroupAndCheckItem(checkGroupId,checkitemId);
            }
        }
    }
}
